import React, {FC, useCallback, useMemo} from "react";
import "./css/CTableOptBtn.less";
import {Button, Tooltip} from "antd";
import GlobalIcon from "../GlobalIcon.tsx";
import {coreConnect} from "../../utils/StoreUtil.tsx";
import {BtnFlow} from "../../services/BtnFlowService.tsx";
import {getLocale} from "../../../i18n/i18n.tsx";
import {validFun} from "../../utils";

interface CTableOptBtnProps {
    node: any,
    btns?: any[],
    align: string,
    ds: any,
    menuBtnMap: any
}

const CTableOptBtn: FC<CTableOptBtnProps> = (props) => {

    const handleBtnClick: Function = useCallback((domEvent: any, menu: any, node: any) => {
        const {ds = {}}: { ds: any } = props;
        menu["data-menu-id"] = menu.id;
        BtnFlow(domEvent.target, {...ds, checkRows: () => ([node])}, menu).flow();
    }, [props.ds]);

    const renderCTableOptBtn = useMemo(() => {
        const {btns, align = "left"}: { btns?: any[], align: string } = props;
        if (!btns) {
            return null;
        }
        return (
            <div className="sf_core_table_opt_btns" style={{textAlign: align}}>
                {btns.map((i: any) => {
                    if (!props.menuBtnMap) {
                        return null
                    }
                    let menu: any = props.menuBtnMap[i.menuId],
                        isShow = true;
                    if (i.validObj) {
                        isShow = validFun(props.node, i.validObj);
                    }
                    if (!menu || !isShow) {
                        return null
                    }
                    if (menu.parentId !== props.ds.menuId) {
                        return null
                    }
                    menu.title = getLocale(menu.zhCn, menu.usEn, menu.ptBr);
                    return (
                        <Tooltip placement="top" title={menu.title}>
                            <Button type="link" icon={menu.icon ? <GlobalIcon name={menu.icon}/> : null}
                                    ref={(ref: any) => {
                                        if (!ref) return;
                                        ref.onclick = (e: any) => {
                                            e.stopPropagation();
                                            handleBtnClick(e, menu, props.node)
                                        }
                                    }}
                            >
                                {!menu.icon ? menu.title : ""}
                            </Button>
                        </Tooltip>
                    )
                })}
            </div>
        )
    }, [props.node, props.btns, props.menuBtnMap, props.ds]);

    return (renderCTableOptBtn);
};

export default coreConnect("menuReducer")(React.memo(CTableOptBtn));